package com.ruoyi.service.impl;

import com.auth0.jwt.JWT;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.libb.entity.User;
import com.ruoyi.libb.utils.AppException;
import com.ruoyi.libb.utils.AppExceptionCodeMsg;
import com.ruoyi.libb.utils.JwtUtil;
import com.ruoyi.libb.utils.Result;
import com.ruoyi.mapper.LoginMapper;
import com.ruoyi.service.LoginService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result login(User user) throws UnsupportedEncodingException {

        User dbUser=loginMapper.login(user);
        if (dbUser==null){

            return Result.error(20001,"账号或密码错误!");
        }

        if (!bCryptPasswordEncoder.matches(user.getPassword(), dbUser.getPassword())){


            return Result.error(20001,"账号或密码错误!");
        }

      /*  String token = JwtUtil.sign(dbUser.getId()+"",dbUser.getUsername(), "libb");*/

        Map<String, Object> map = new HashMap<>();
        map.put("userid",String.valueOf(dbUser.getId()));
        map.put("username",dbUser.getUsername());
        String token = JwtUtils.createToken(map);



        redisTemplate.opsForValue().set(token,token,5, TimeUnit.MINUTES);
        new AppException(AppExceptionCodeMsg.ERROR_LOGIN_NOT);
        return Result.success(token);
    }
}
